<template>
	<view class="family-member-page">
		<!-- 表单容器：配置验证规则 -->
		<u-form :model="formData" :rules="formRules" ref="familyForm" label-position="top">
			<!-- 真实姓名（必填） -->
			<u-form-item prop="name">
				<template #label>
					真实姓名<span class="required">*</span>
				</template>
				<u-input v-model="formData.name" placeholder="请填写您的真实姓名" />
			</u-form-item>

			<!-- 身份证号（必填） -->
			<u-form-item prop="IDnumber">
				<template #label>
					身份证号<span class="required">*</span>
				</template>
				<u-input v-model="formData.IDnumber" placeholder="请填写您的身份证号" type="idcard" />
			</u-form-item>

			<!-- 性别（必填，单选） -->
			<u-form-item prop="gender">
				<template #label>
					性别<span class="required">*</span>
				</template>
				<view @click="genderShow = true" class="picker-trigger">
					{{ formData.gender || '请选择性别' }}
				</view>
				<u-picker :show="genderShow" :columns="genderColumns" @confirm="onGenderConfirm"
					@cancel="genderShow = false"></u-picker>
			</u-form-item>

			<!-- 出生日期（必填，日期选择） -->
			<u-form-item prop="birthday">
				<template #label>
					出生日期<span class="required">*</span>
				</template>
				<view @click="showBirthdayPicker = true" class="picker-trigger">
					{{ formData.birthday || '请选择' }}
				</view>
				<u-datetime-picker :min-date="-2208988800000" :max-date="1767139200000" :show="showBirthdayPicker"
					mode="date" @confirm="handleBirthdayConfirm"
					@cancel="showBirthdayPicker = false"></u-datetime-picker>
			</u-form-item>

			<!-- 联系电话（必填） -->
			<u-form-item prop="phone">
				<template #label>
					联系电话<span class="required">*</span>
				</template>
				<u-input v-model="formData.phone" placeholder="请填写联系电话" type="number" />
			</u-form-item>

			<!-- 现居地（选填） -->
			<u-form-item prop="address">
				<template #label>现居地</template>
				<u-input v-model="formData.address" placeholder="请填写现居住地址" />
			</u-form-item>

			<!-- 与本人关系（必填） -->
			<u-form-item prop="relationship">
				<template #label>
					与本人关系<span class="required">*</span>
				</template>
				<view @click="relationshipShow = true" class="picker-trigger">
					{{ formData.relationship || '请选择和您的关系' }}
				</view>
				<u-picker :show="relationshipShow" :columns="relationshipColumns" @confirm="onRelationConfirm"
					@cancel="relationshipShow = false"></u-picker>
			</u-form-item>

			<!-- 密码（必填） -->
			<u-form-item prop="password">
				<template #label>
					密码<span class="required">*</span>
				</template>
				<u-input v-model="formData.password" placeholder="请输入密码（8-20位，含字母和数字）" type="password" />
			</u-form-item>

			<!-- 保存按钮 -->
			<u-form-item>
				<u-button type="primary" block @click="handleSave">保存</u-button>
			</u-form-item>
		</u-form>

		<!-- 提示组件 -->
		<u-toast ref="toast" />
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue';
	import {
		useUserStore
	} from '../../../store/user';

	// 表单数据
	const formData = ref({
		name: '',
		IDnumber: '',
		gender: '',
		birthday: '',
		phone: '',
		address: '',
		relationship: '',
		password: '',
	});
	const relationshipShow = ref(false);
	const showBirthdayPicker = ref(false);
	const genderShow = ref(false);

	// 性别选择器数据
	const genderColumns = reactive([
		[{
			text: '男',
			value: '1'
		}, {
			text: '女',
			value: '0'
		}]
	]);
	// 与本人关系选项
	const relationshipColumns = reactive([
		[{
			text: '父母',
			value: '父母'
		}, {
			text: '夫妻',
			value: '夫妻'
		}, {
			text: '子女',
			value: '子女'
		}, {
			text: '兄弟',
			value: '兄弟'
		}, {
			text: '其他关系',
			value: '其他关系'
		}]
	]);

	// 性别选择确认
	const onGenderConfirm = (sex) => {
		formData.value.gender = sex.value[0].text; // 获取选中的文本值
		genderShow.value = false;
	};


	// 关系选择确认
	const onRelationConfirm = (relation) => {
		formData.value.relationship = relation.value[0].text;
		relationshipShow.value = false;
	};

	// 出生日期确认
	const handleBirthdayConfirm = (val) => {
		const date = new Date(val.value);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		formData.value.birthday = `${year}-${month}-${day}`;
		showBirthdayPicker.value = false;
	};

	// 表单验证规则（增强版）
	const formRules = ref({
		name: [{
			required: true,
			message: '请填写真实姓名',
			trigger: 'blur'
		}],
		IDnumber: [{
				required: true,
				message: '请填写身份证号',
				trigger: 'blur'
			},
			{
				pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
				message: '请输入正确的身份证号码',
				trigger: 'blur'
			}
		],
		gender: [{
			required: true,
			message: '请选择性别',
			trigger: 'change'
		}],
		birthday: [{
			required: true,
			message: '请选择出生日期',
			trigger: 'change'
		}],
		phone: [{
				required: true,
				message: '请填写联系电话',
				trigger: 'blur'
			},
			{
				pattern: /^1[3-9]\d{9}$/,
				message: '请输入正确的手机号码',
				trigger: 'blur'
			}
		],
		relationship: [{
			required: true,
			message: '请选择与本人关系',
			trigger: 'change'
		}],
		password: [{
				required: true,
				message: '请输入密码',
				trigger: 'blur'
			},
			{
				// 正则说明：8-20位，包含至少1个字母（大小写均可）和1个数字
				pattern: /^(?=.*[A-Za-z])(?=.*\d).{8,20}$/,
				message: '密码需8-20位，包含字母和数字',
				trigger: 'blur'
			}
		]
	});

	// 表单引用和提示组件引用
	const familyForm = ref(null);
	const toast = ref(null);



	const userStore = useUserStore()
	// 保存逻辑：提交成功后重置表单，允许继续添加
	const handleSave = async () => { // 改为async函数
		try {
			// 表单验证（使用await等待验证结果）
			const valid = await familyForm.value.validate();
			if (valid) { // 验证通过
				// 显示加载提示（可选，提升体验）
				uni.showLoading({
					title: '保存中...'
				});

				// 发送请求
				uni.request({
					url: 'http://nocat.life:3012/relations/addFamily',
					method: 'POST',
					data: {
						residentId: userStore.userInfo._id, // 当前登录用户 ID
						name: formData.value.name,
						IDnumber: formData.value.IDnumber,
						gender: formData.value.gender === '男' ? '1' : '0',
						birthday: formData.value.birthday,
						phone: formData.value.phone,
						address: formData.value.address,
						relationship: formData.value.relationship,
						password: formData.value.password,
					},
					success: (res) => {
						if (res.statusCode === 200) {
							// 直接返回上一页面
							uni.navigateBack();
						} else {
							toast.value.show({
								title: res.data.message || '添加失败',
								type: 'error',
								duration: 2000
							});
						}
					},
					fail: (err) => {
						toast.value.show({
							title: '网络错误，请重试',
							type: 'error',
							duration: 2000
						});
						console.error('添加失败：', err);
					},
					complete: () => {
						uni.hideLoading(); // 隐藏加载
					}
				});
			}
		} catch (err) {
			// 验证失败（err包含未通过的字段信息）
			console.log('表单验证失败：', err);
			// 可在此处显示总体错误提示
			toast.value.show({
				title: '请完善必填信息',
				type: 'warning',
				duration: 2000
			});
		}
	};
</script>


<style scoped>
	/* 页面容器 */
	.family-member-page {
		padding: 32rpx;
		/* 整体内边距 */
		background-color: rgba(242, 247, 251, 0.619607843137255);
	}

	/* 表单项间距 & 标签样式 */
	::v-deep .u-form-item {
		margin-bottom: 30rpx;
		/* 项与项的间距 */
	}

	::v-deep .u-form-item__label {
		font-size: 32rpx;
		/* 标签字号 */
		color: #333;
		/* 标签颜色 */
		line-height: 1.2;
		/* 行高 */
	}

	/* 红色星号 */
	.required {
		color: #ff4d4f;
		/* 星号颜色 */
		margin-left: 4rpx;
		/* 与标签的间距 */
	}

	/* 输入框/选择器通用样式：边框、圆角、内边距 */
	::v-deep .u-input__wrap,
	::v-deep .u-picker__wrap,
	::v-deep .u-date-picker__wrap {

		border: 1px solid #eee;
		/* 浅灰色边框 */
		border-radius: 10rpx;
		/* 圆角 */
		padding: 24rpx;
		/* 内边距 */
		font-size: 28rpx;
		/* 内容字号 */
		color: #999;
		/* 占位符颜色 */
	}

	/* 联系电话默认值颜色 */
	::v-deep .u-input__value {
		color: #333;
		/* 默认值显示为深色 */
	}

	/* 性别单选：横向排列 + 间距 */
	::v-deep .u-radio-group {
		display: flex;
		flex-direction: row;
		/* 横向排列 */
		align-items: center;
	}

	::v-deep .u-radio {
		margin-right: 30rpx;
		/* 选项间距 */
	}

	/* 单选框大小调整 */
	::v-deep .u-radio__icon {
		width: 32rpx;
		height: 32rpx;
	}

	/* 保存按钮：尺寸、圆角 */
	::v-deep .u-button--primary {
		height: 88rpx;
		/* 按钮高度 */
		font-size: 32rpx;
		/* 按钮文字大小 */
		border-radius: 10rpx;
		/* 按钮圆角 */
	}

	/* Picker 触发区域样式：模拟输入框外观 */
	.picker-trigger {
		width: 89vw;
		border: 1px solid #eee;
		border-radius: 10rpx;
		padding: 10rpx;
		font-size: 28rpx;
		color: #999;
		min-height: 60rpx;
		/* 与输入框高度对齐 */
		display: flex;
		align-items: center;
	}
</style>